<?php
//-------------------------------------------------------------------------------------------------------
    require_once($config['app_dir'] . "/includes/object.class.php");
    require_once($config['app_dir'] . "/classes/staff.class.php");
    require_once($config['app_dir'] . "/classes/DataLists.class.php");
    require_once($config['app_dir'] . "/includes/db.class.php");
    //---------------------------------------------------------------------------------------------------
    abstract class objAbstractCollector implements iDebug  {
            static protected $prefix = 'AbstractCollector_';
            protected $Session = false;

        protected function __construct() {
         global $config;
            $this->Session = $this->Session = new objSession($config['app_id']);
        } //constructor

         public static function GetInstance() {
            if (!isset(self::$instance)) {
                //$c = __CLASS__;
                $c =  self::ClassName();
                self::$instance = new $c;
            }
            return self::$instance;
        } //GetInstance

        public function __clone()    {
            throw new Exception('Cant clone singleton');
        } //clone

        public  function Lock() {
            $this->Session->Put($this->prefix . 'lock', '1');
        } //Lock

        public function Unlock() {
            $this->Session->Put($this->prefix . 'lock', '0');
        } //Unlock

        public function isLocked() {
            return $this->Session->Get($this->prefix . 'lock');
        } //Unlock

        public function IncCounter() {
            $this->Session->Put($this->prefix . 'count', 1 + $this->getCounter());
        } //IncCounter

        public function getCounter() {
            return intval($this->Session->Get($this->prefix . 'count'));
        } //getCounter

        abstract public function isEmpty($aName=false);

        abstract public function Clear($aName=false);

        public function ClearAll() {
            $this->Clear();
        } //ClearAll

        abstract static protected function ClassName();

    } //class AbstractCollector

    //-----------------------------------------------------------------------------------------------------

    class objArchiveCollector extends objAbstractCollector implements iDebug {
            private static $instance;
            static protected $prefix = 'SelectedArchiveItems_';
            protected $Session = false;
            protected $_fields = array('system', 'year', 'month', 'pair', 'part');

        static protected function ClassName() {
            return __CLASS__;
        } //ClassName


        public function dump() {
            foreach($this->_fields as $aField) {
                echo "\n $aField: ";
                var_dump($this->getValue($aField));
            } //foreach
        }//dump

       //----------------------------------------------------------------------------------------

        public function __set($aName, $aValue) {
            $this->setValue($aName, $aValue);
        } //setter

        public function __get($aName) {
            return $this->getValue($aName);
        } //getter


        public function Clear($aName=false) {
            if( $aName ) {
                $this->setValue($aName, false);
            } else {
                foreach($this->_fields as $aField) {
                    $this->setValue($aField, false);
                } //foreach
            }
        } //Clear

        public function setValue($aName, $aValue) {
            if( $this->isField($aName) )
                $this->Session->Put($this->prefix . strtolower($aName), $aValue);
        } //setValue

        public function getValue($aName) {
            if( $this->isField($aName) )
                return $this->Session->Get($this->prefix . strtolower($aName));
            else
                return false;
        } //getValue

        public function isField($aName) {
            return in_array(strtolower($aName), $this->_fields);
        } //isField

        //----------------------------------------------------------------------------------------

        public function isEmpty($aName=false) {
            $result = true;
            if( $aName ) {
                $aValue = $this->getValue($aName);
                $result = $result && ( empty($aValue) || !$aValue );
            } else {
                foreach($this->_fields as $aField) {
                    $aValue = $this->getValue($aField);
                    $result = $result && ( empty($aValue) || !$aValue );
                } //foreach
            }
            return $result;
        } //isEmpty

    }//class ArchiveCollector
    //---------------------------------------------------------------------------------------------------
    class objArchiveDispatcher {
            private static $instance;
            public $Collector = false;

            protected $Response = false;
            protected $_systems_full = false;
            protected $_pairs_full = false;
            protected $_years_full = false;
            protected $_months_full = array('MonthID'=> 1,
                                            'MonthID'=> 2,
                                            'MonthID'=> 3,
                                            'MonthID'=> 4,
                                            'MonthID'=> 5,
                                            'MonthID'=> 6,
                                            'MonthID'=> 7,
                                            'MonthID'=> 8,
                                            'MonthID'=> 9,
                                            'MonthID'=>10,
                                            'MonthID'=>11,
                                            'MonthID'=>12);

            protected $_parts_full = array('PartID'=>1,
                                           'PartID'=>2);

            protected $_systems = false;
            protected $_pairs = false;
            protected $_years = false;
            protected $_months = false;
            protected $_parts = array(1,2);

            protected $DataBase = false;
            protected $_sql_querys = array();

        protected function __construct() {
            $this->Collector =  objArchiveCollector::GetInstance();
            $this->DataBase = objDataBase::GetInstance();
        } //constructor

        public static function GetInstance() {
            if (!isset(self::$instance)) {
                $c = __CLASS__;
                self::$instance = new $c;

            }
            return self::$instance;
        } //GetInstance

        public function __clone()    {
            throw new Exception('Cant clone singleton');
        } //clone

        //----------------------------------------------------------------------------------------------
        protected function PrepareFull() {
            $this->_sqls(false);

            $this->_systems_full = $this->DataBase->handler->CacheGetAll(60, $this->_sql_querys['systems']);
            $this->_pairs_full = $this->DataBase->handler->CacheGetAll(60, $this->_sql_querys['pairs']);
            $this->_years_full = $this->DataBase->handler->CacheGetAll(60, $this->_sql_querys['years']);
            $this->_months_full = $this->DataBase->handler->CacheGetAll(60, $this->_sql_querys['months']);
            $this->_parts_full = $this->DataBase->handler->CacheGetAll(60, $this->_sql_querys['parts']);
        } //PrepareFull

        protected function Prepare($mode='all') {
            $this->_sqls(true);

            $mode = strtolower($mode);

            if('all'==$mode || 'system'==$mode) {
                $this->_systems = $this->DataBase->handler->getAll($this->_sql_querys['systems']);
                //$this->setDefault('system');
            }

            if('all'==$mode || 'pair'==$mode) {
                $this->_pairs = $this->DataBase->handler->getAll($this->_sql_querys['pairs'],
                                                            array(
                                                                  $this->Collector->system)
                                                            );
                //$this->setDefault('pair');
            }

            if('all'==$mode || 'year'==$mode) {
                $this->_years = $this->DataBase->handler->getAll($this->_sql_querys['years'],
                                                            array($this->Collector->system,
                                                                $this->Collector->pair)
                                                            );
                //$this->setDefault('year');
            }

            if('all'==$mode || 'month'==$mode) {
                $this->_months = $this->DataBase->handler->getAll($this->_sql_querys['months'],
                                                            array($this->Collector->system,
                                                                $this->Collector->pair,
                                                                $this->Collector->year)
                                                            );
                //$this->setDefault('month');
            }

            if('all'==$mode || 'part'==$mode) {
                $this->_parts = $this->DataBase->handler->getAll($this->_sql_querys['parts'],
                                                            array($this->Collector->system,
                                                                $this->Collector->pair,
                                                                $this->Collector->year,
                                                                $this->Collector->month
                                                                )
                                                           );
                //$this->setDefault('part');
            }
        } //Prepare

        public function setDefault($aName, $force=false) {
            switch( strtolower($aName) ) {
                case 'system':
                    $aValue = $this->_systems[0]['SystemID'];
                break;
                //-------------------------------------------------------------------------------------
                case 'pair':
                    $aValue = $this->_pairs[0]['TradeID'];
                break;
                //-------------------------------------------------------------------------------------
                case 'month':
                    $aValue = $this->_months[0]['MonthID'];
                break;
                //-------------------------------------------------------------------------------------
                case 'year':
                    $aValue = $this->_years[0]['YearID'];
                break;
                //-------------------------------------------------------------------------------------
                case 'part':
                    $aValue = $this->_parts[0]['PartID'];
                break;
                //-------------------------------------------------------------------------------------
                default: return false;
            } //switch

            if( $force || $this->Collector->isEmpty($aName) )  $this->Collector->setValue($aName, $aValue);
        } //setDefault

        public function StartResponse() {
            $this->Response= new xajaxResponse();
        } //StartRespone

        public function Render($aTemplateFileName='_archive.tpl') {
            $this->PrepareFull();

            $Template = new objTemplate();

            $Template->Assign('SystemsAllArr', $this->_systems_full);
            $Template->Assign('PairsAllArr', $this->_pairs_full);
            $Template->Assign('YearsAllArr', $this->_years_full);
            $Template->Assign('MonthsAllArr', $this->_months_full);
            $Template->Assign('PartsAllArr', $this->_parts_full);

            return $Template->Fetch($aTemplateFileName);
        }//Render
        //----------------------------------------------------------------------------------------------

        protected function ReloadSelectItem($fullArr, $sellectedArr,  $divPrefix,  $fieldKey,  $collectorKey) {

            foreach($fullArr as $item) {
                $this->Response->AddAssign($divPrefix . $item[$fieldKey].'_separator', 'style.display', 'none');

                $this->Response->AddAssign($divPrefix . $item[$fieldKey].'_normal', 'style.display', 'none');
                $this->Response->AddAssign($divPrefix . $item[$fieldKey].'_selected', 'style.display', 'none');
            } //foreach systems

            $first = true;
            foreach($sellectedArr as $item) {
                if( !$first ) {
                    $this->Response->AddAssign($divPrefix . $item[$fieldKey].'_separator', 'style.display', 'inline');
                } else $first = false;
                if( $item[$fieldKey]!=$this->Collector->getValue($collectorKey) )
                    $this->Response->AddAssign($divPrefix . $item[$fieldKey].'_normal', 'style.display', 'inline');
                else
                    $this->Response->AddAssign($divPrefix . $item[$fieldKey].'_selected', 'style.display', 'inline');
            } //foreach months

            return $this->Response;
        } //ReloadSelectItem

        public function ReloadMonths() {
            $this->ReloadSelectItem($this->_months_full, $this->_months, 'divArchiveMonth_', 'MonthID', 'month');
        } //ReloadMonths

        public function ReloadYears() {
            $this->ReloadSelectItem($this->_years_full, $this->_years, 'divArchiveYear_', 'YearID', 'year');
        } //ReloadYears

        public function ReloadPairs() {
            $this->ReloadSelectItem($this->_pairs_full, $this->_pairs, 'divArchivePair_', 'TradeID', 'pair');
        } //ReloadPairs

        public function ReloadSystems() {
            $this->ReloadSelectItem($this->_systems_full, $this->_systems, 'divArchiveSystem_', 'SystemID', 'system');
        } //ReloadSystems

        public function ReloadParts() {
            $this->ReloadSelectItem($this->_parts_full, $this->_parts, 'divArchivePart_', 'PartID', 'part');
        } //ReloadParts

        public function ReloadMain() {
            $result = '';
            $system = $this->Collector->getValue('system');
            $result .=  $system . '|' ;
            $trade = $this->Collector->getValue('pair');
            $result .=  $trade . '|' ;
            $year = $this->Collector->getValue('year');
            $result .= $year . '|' ;
            $month = $this->Collector->getValue('month');
            $result .=  $month . '|' ;
            $part = $this->Collector->getValue('part');
            $result .= $part . '|' ;
            if( 1==$part) {
                $start =  DateConvert::Date('Y-m-d', mktime(0,0,0, $month, 1, $year));
                $finish =  DateConvert::Date('Y-m-d', mktime(0,0,0, $month, 16, $year));
            } else {
                $start =  DateConvert::Date('Y-m-d', mktime(0,0,0, $month, 15, $year));
                $month++;
                if($month>12) { $month=1; $year+=1;}
                $finish =  DateConvert::Date('Y-m-d', mktime(0,0,0, $month, 1, $year));
            }
            $result .= "period= $start-$finish";
            $image = "<img alt=\"Forecast.gif\" width=\"800\" height=\"500\" style=\"border: #CCCCCC 1px solid;\"".
                "src=\"/history_forecast.php?trade=$trade&start=$start&finish=$finish&system=$system\"></img>";

            $this->Response->addAssign('divArchiveMain','innerHTML', $result.'<br>'.$image);

            return $this->Response;
        } //ReloadMain

        public function changeSystem($aValue=false) {
            $this->StartResponse();
            if( !$aValue ) {
                $this->Collector->ClearAll();
                $this->PrepareFull();
                $this->Prepare('system');
                $this->setDefault('system', true);

            } else   {
                $this->PrepareFull();
                $this->Prepare('system');

                $this->Collector->system = $aValue;
            }

            $this->Prepare('pair');
            $this->setDefault('pair', true);
            $this->Prepare('year');
            $this->setDefault('year', true);
            $this->Prepare('month');
            $this->setDefault('month', true);
            $this->Prepare('part');
            $this->setDefault('part', true);

            $this->ReloadSystems();
            $this->ReloadPairs();
            $this->ReloadYears();
            $this->ReloadMonths();
            $this->ReloadParts();

            $this->ReloadMain();

            return $this->Response;
        } //changeSystem

        public function changePair($aValue) {
            $this->Collector->pair = $aValue;

            $this->PrepareFull();
            $this->Prepare('pair');

            $this->Prepare('year');
            $this->setDefault('year', true);
            $this->Prepare('month');
            $this->setDefault('month', true);
            $this->Prepare('part');
            $this->setDefault('part', true);

            $this->StartResponse();

            $this->ReloadPairs();
            $this->ReloadYears();
            $this->ReloadMonths();
            $this->ReloadParts();

            $this->ReloadMain();

            return $this->Response;
        } //changePair

        public function changeYear($aValue) {
            $this->Collector->year = $aValue;
            $this->PrepareFull();
            $this->Prepare('year');

            $this->Prepare('month');
            $this->setDefault('month', true);
            $this->Prepare('part');
            $this->setDefault('part', true);

            $this->StartResponse();

            $this->ReloadYears();
            $this->ReloadMonths();
            $this->ReloadParts();

            $this->ReloadMain();

            return $this->Response;
        } //changeYear

        public function changeMonth($aValue) {
            $this->Collector->month = $aValue;
            $this->PrepareFull();

            $this->Prepare('month');

            $this->Prepare('part');
            $this->setDefault('part', true);

            $this->StartResponse();

            $this->ReloadMonths();
            $this->ReloadParts();
            $this->ReloadMain();

            return $this->Response;
        } //changePair

        public function changePart($aValue) {
            $this->Collector->part = $aValue;

            $this->PrepareFull();
            $this->Prepare('part');

            $this->StartResponse();

            $this->ReloadParts();
            $this->ReloadMain();

            return $this->Response;
        } //changePart

        protected function _sqls($params=false) {
            $this->_sql_querys['systems'] =
             " SELECT ".
              " s.SystemID, ".
              " s.Name ".
             " FROM fa_systems s ".
             " WHERE s.Active=1 ";
            //------------------------------------------------------------------------------------------
            $this->_sql_querys['pairs'] =
             " SELECT ".
                    " t.TradeID, ".
                    " t.Pair ".
             " FROM  ".
                " fa_trades_systems ts   ".
                " LEFT OUTER JOIN fa_systems s ON (ts.SystemID = s.SystemID AND s.Active=1)    ".
                " LEFT OUTER JOIN fa_trades t ON (ts.TradeID = t.TradeID)  ".
             " WHERE (1=1) ".
             ($params ? " AND s.SystemID=? ":'').
             " ORDER BY t.TradeID ";
            //------------------------------------------------------------------------------------------
            $this->_sql_querys['years'] =
             " SELECT DISTINCT YEAR(FROM_UNIXTIME(f.BeginTime)) as YearID ".
             " FROM vfa_forecast f ".
             " WHERE (1=1) ".
             ($params ? " AND f.SystemID=? AND f.TradeID=? ":'').
             " ORDER BY f.BeginTime ASC ";
            //------------------------------------------------------------------------------------------
            $this->_sql_querys['months'] =
             " SELECT DISTINCT MONTH(FROM_UNIXTIME(f.BeginTime)) as MonthID ".
             " FROM vfa_forecast f ".
             " WHERE (1=1) ".
             ($params ? " AND f.SystemID=? AND f.TradeID=? AND YEAR(FROM_UNIXTIME(f.BeginTime))=? ":'').
             " ORDER BY MONTH(FROM_UNIXTIME(f.BeginTime)) ASC  ";
            //------------------------------------------------------------------------------------------
            $this->_sql_querys['parts'] =
             " SELECT DiSTINCT	1+sign(1+sign(DAY(FROM_UNIXTIME(f.BeginTime))-15))	as PartID ".
             " FROM vfa_forecast f ".
             " WHERE (1=1) ".
             ($params ? "AND f.SystemID=? AND f.TradeID=? AND YEAR(FROM_UNIXTIME(f.BeginTime))=?  AND MONTH(FROM_UNIXTIME(f.BeginTime))=? ":'').
             " ORDER BY 1+sign(1+sign(DAY(FROM_UNIXTIME(f.BeginTime))-15)) ASC ";
        } //_sqls

    } //class ArchiveDispatcher
    //---------------------------------------------------------------------------------------------------
    function ArchiveChangeSystem($aValue=false) {
        return objArchiveDispatcher::GetInstance()->changeSystem($aValue);
    } //ArchiveChangeSystem

    function ArchiveChangePair($aValue) {
        return objArchiveDispatcher::GetInstance()->changePair($aValue);
    } //ArchiveChangePair

    function ArchiveChangeYear($aValue) {
        return objArchiveDispatcher::GetInstance()->changeYear($aValue);
    } //ArchiveChangeYear

    function ArchiveChangeMonth($aValue) {
        return objArchiveDispatcher::GetInstance()->changeMonth($aValue);
    } //ArchiveChangeMonth

    function ArchiveChangePart($aValue) {
        return objArchiveDispatcher::GetInstance()->changePart($aValue);
    } //ArchiveChangePart

//-------------------------------------------------------------------------------------------------------
?>
